package com.itheima.blog.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.blog.auth.dao.AdminUserMapper;
import com.itheima.blog.auth.dto.LoginReqDto;
import com.itheima.blog.auth.dto.LoginResDTO;
import com.itheima.blog.auth.dto.UserDto;
import com.itheima.blog.auth.entity.AdminUser;
import com.itheima.blog.auth.service.AdminUserService;
import com.itheima.blog.util.BeanHelper;
import com.itheima.blog.util.JwtUtils;
import com.itheima.blog.util.constants.Constants;
import com.itheima.blog.util.constants.ErrorInfo;
import com.itheima.common.exception.BlogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-05-25
 */
@Service
public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService {

    @Autowired
    private BCryptPasswordEncoder encoder;

    @Override
    public LoginResDTO login(LoginReqDto dto) {
        // 根据用户名查用户信息
        LambdaQueryWrapper<AdminUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminUser::getName, dto.getName());
        AdminUser userDB = this.getOne(queryWrapper);
        if(userDB == null){
            throw new BlogException(ErrorInfo.Msg.USER_NOT_EXISTS);
        }
        // 密码的匹配
        String passwordDB = userDB.getPassword();
        String passwordInput = dto.getPassword();
        boolean matches = encoder.matches(passwordInput, passwordDB);
        if(!matches){
            throw new BlogException(ErrorInfo.Msg.PASSWORD_ERROR);
        }
        // 生成token，user返回
        LoginResDTO result = new LoginResDTO();
        result.setUser(BeanHelper.copyProperties(userDB, UserDto.class));
        result.setToken(JwtUtils.generateTokenExpireInMinutes(userDB.getId(), Constants.EXPIRE_MINUTE));
        return result;
    }
}
